package com.zhuangxiaoyan.springboot.jpa.domian.model;

import lombok.Data;
import lombok.EqualsAndHashCode;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Table;
import java.io.Serializable;
import java.time.LocalDateTime;

/**
 * User
 *
 * @author xjl
 * @version 2025/01/13 23:07
 **/
@Entity
@Table(name = "user")
@Data
@EqualsAndHashCode
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private int id;

    @Column(nullable = false, unique = true)
    private String email;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false)
    private LocalDateTime gmtCreate;

    @Column(nullable = false)
    private LocalDateTime gmtModify;

    // 在实体第一次持久化到数据库时（即插入时），设置 gmtCreate 和 gmtModify
    @PrePersist
    public void prePersist() {
        LocalDateTime now = LocalDateTime.now();
        if (gmtCreate == null) {
            gmtCreate = now;
        }
        if (gmtModify == null) {
            gmtModify = now;
        }
    }

    // 在实体每次更新时，更新 gmtModify
    @PreUpdate
    public void preUpdate() {
        gmtModify = LocalDateTime.now();
    }
}